package juc;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Future 在实际使用过程中存在一些局限性，比如不支持异步任务的编排组合、获取计算结果的 get() 方法为阻塞调用。
 * 还提供了函数式编程、异步任务编排组合（可以将多个异步任务串联起来，组成一个完整的链式调用）等能力
 * runAsync   无返回值
 * supplyAsync  有返回值
 */
public class CompletableFutureTest {

    private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(
            1,
            9,
            0,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {
        List<String> listStr = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            int finalNum = i;
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                System.out.println("开始处理任务......" + finalNum);
                if (finalNum % 2 ==0){
                    try {
                        Thread.sleep(5000 );
                    } catch (InterruptedException e) { }
                }
                return "处理的任务:" + finalNum;
            }, executorService);
            listStr.add(future.join());
        }
        System.out.println(JSONObject.toJSON(listStr));
    }
}

